<template>
   <div class="main">
      <div class="app-container">
         <a-card title="个人信息">
            <a-row>
               <a-col :lg="8">
                  <span class="subject_label">登录账号</span>
                  <span class="subject_value">{{ user_info.userName }}</span>
               </a-col>
               <a-col :lg="8" v-if="user_info.nickName">
                  <span class="subject_label">用户昵称</span>
                  <span class="subject_value">{{ user_info.nickName }}</span>
               </a-col>
               <a-col :lg="8" v-if="user_info.phonenumber">
                  <span class="subject_label">联系方式</span>
                  <span class="subject_value">{{ user_info.phonenumber }}</span>
               </a-col>
            </a-row>
         </a-card>
         <a-card title="运营商信息" class="mt10">
            <template #extra>
               <el-button type="primary" @click="handleUpdateMine(subject_info)">更新运营商信息</el-button>
            </template>
            <a-row>
               <a-col :lg="8">
                  <span class="subject_label">运营商名称</span>
                  <span class="subject_value">{{ subject_info.subjectName }}</span>
               </a-col>
               <a-col :lg="8">
                  <span class="subject_label">客服电话</span>
                  <span class="subject_value">{{ subject_info.contact }}</span>
               </a-col>
            </a-row>
            <a-row class="mt10" v-if="subject_info.wallet && subject_info.wallet.useFlag == true">
               <a-col :lg="24">
                  <span class="subject_label">账户余额</span>
                  <span class="subject_value">{{ subject_info.wallet.balance / 100 || 0 }}元</span>
               </a-col>
               <a-col :lg="24" class="mt10">
                  <el-button type="primary" @click="gotoWalletLog">钱包日志</el-button>
                  <el-button class="ml10" type="primary" @click="gotoSeparate">分账账单</el-button>
                  <span class="ml10" v-if="subject_info.wallet && subject_info.wallet.useFlag == true">
                     <el-button type="success" @click="handleWithdrawal"
                        v-hasPermi="['system:subject:withdrawal']">提现</el-button>
                  </span>
                  <el-button class="ml10" type="primary" @click="gotoWithdrawalLog">提现日志</el-button>
               </a-col>
            </a-row>
         </a-card>
         <a-card title="主体列表" class="mt10" v-if="subject_type == 'SP'">
            <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
               <el-form-item label="主体名称" prop="subjectName">
                  <el-input v-model="queryParams.subjectName" placeholder="请输入主体名称" clearable style="width: 200px"
                     @keyup.enter="handleQuery" />
               </el-form-item>
               <el-form-item label="状态" prop="delFlag">
                  <el-select v-model="queryParams.delFlag" placeholder="状态" clearable style="width: 200px">
                     <el-option v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.label"
                        :value="dict.value" />
                  </el-select>
               </el-form-item>
               <el-form-item>
                  <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                  <el-button icon="Refresh" @click="resetQuery">重置</el-button>
               </el-form-item>
            </el-form>

            <el-row :gutter="10" class="mb8">
               <el-col :span="1.5">
                  <el-button type="primary" plain icon="Plus" @click="handleAdd"
                     v-hasPermi="['system:subject:add']">新增</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button plain icon="Plus" @click="handleCreate"
                     v-hasPermi="['system:subject:addUser']">生成注册码</el-button>
               </el-col>
               <el-col :span="1.5">
                  <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
               </el-col>
               <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
            </el-row>

            <el-table v-if="refreshTable" v-loading="loading" :data="subjectList" row-key="subjectId"
               :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
               <el-table-column prop="subjectName" label="主体名称" width="260" />
               <el-table-column prop="contact" label="客服电话" width="260" />
               <el-table-column prop="orderNum" label="排序" width="200" />
               <el-table-column prop="delFlag" label="状态" width="100">
                  <template #default="scope">
                     <dict-tag :options="sys_normal_disable" :value="scope.row.delFlag" />
                  </template>
               </el-table-column>
               <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                  <template #default="scope">
                     <span>{{ parseTime(scope.row.createTime) }}</span>
                  </template>
               </el-table-column>
               <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:subject:edit']">修改</el-button>
                     <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                        v-hasPermi="['system:subject:add']">新增</el-button>
                     <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete"
                        @click="handleDelete(scope.row)" v-hasPermi="['system:subject:remove']">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
         </a-card>
         <a-card title="主体列表" class="mt10" v-if="subjectData.length > 1 && subject_type != 'SP'">
            <el-table v-if="refreshTable" v-loading="loading" :data="subjectList" row-key="subjectId"
               :default-expand-all="isExpandAll" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
               <el-table-column prop="subjectName" label="主体名称" width="260" />
               <el-table-column prop="contact" label="客服电话" width="260" />
               <el-table-column prop="orderNum" label="排序" width="200" />
               <el-table-column prop="delFlag" label="状态" width="100">
                  <template #default="scope">
                     <dict-tag :options="sys_normal_disable" :value="scope.row.delFlag" />
                  </template>
               </el-table-column>
               <el-table-column label="创建时间" align="center" prop="createTime" width="200">
                  <template #default="scope">
                     <span>{{ parseTime(scope.row.createTime) }}</span>
                  </template>
               </el-table-column>
               <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                     <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:subject:edit']">修改</el-button>
                     <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)"
                        v-hasPermi="['system:subject:add']">新增</el-button>
                     <el-button v-if="scope.row.parentId != 0" link type="primary" icon="Delete"
                        @click="handleDelete(scope.row)" v-hasPermi="['system:subject:remove']">删除</el-button>
                  </template>
               </el-table-column>
            </el-table>
         </a-card>

         <!-- 添加或修改主体对话框 -->
         <el-dialog :title="titleMine" v-model="openMine" width="600px" append-to-body>
            <el-form ref="subjectMineRef" :model="formMine" :rules="rulesMine" label-width="80px">
               <el-row>
                  <el-col :span="12">
                     <el-form-item label="主体名称" prop="subjectName">
                        <el-input v-model="formMine.subjectName" placeholder="请输入主体名称" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="客服电话" prop="contact">
                        <el-input v-model="formMine.contact" placeholder="请输入客服电话" maxlength="11" />
                     </el-form-item>
                  </el-col>
               </el-row>
            </el-form>
            <template #footer>
               <div class="dialog-footer">
                  <el-button type="primary" @click="submitFormMine">确 定</el-button>
                  <el-button @click="cancelMine">取 消</el-button>
               </div>
            </template>
         </el-dialog>

         <!-- 添加或修改主体对话框 -->
         <el-dialog :title="title" v-model="open" width="600px" append-to-body>
            <el-form ref="subjectRef" :model="form" :rules="rules" label-width="80px">
               <el-row>
                  <el-col :span="24" v-if="form.parentId !== 0">
                     <el-form-item label="上级主体" prop="parentId">
                        <el-tree-select v-model="form.parentId" :data="subjectOptions"
                           :props="{ value: 'subjectId', label: 'subjectName', children: 'children' }"
                           value-key="subjectId" placeholder="选择上级主体" check-strictly />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="主体名称" prop="subjectName">
                        <el-input v-model="form.subjectName" placeholder="请输入主体名称" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="显示排序" prop="orderNum">
                        <el-input-number v-model="form.orderNum" controls-position="right" :min="0" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="客服电话" prop="contact">
                        <el-input v-model="form.contact" placeholder="请输入客服电话" maxlength="11" />
                     </el-form-item>
                  </el-col>
                  <el-col :span="12">
                     <el-form-item label="状态">
                        <el-radio-group v-model="form.delFlag">
                           <el-radio v-for="dict in sys_normal_disable" :key="dict.value" :label="dict.value">{{
                              dict.label
                           }}</el-radio>
                        </el-radio-group>
                     </el-form-item>
                  </el-col>
               </el-row>
            </el-form>
            <template #footer>
               <div class="dialog-footer">
                  <el-button type="primary" @click="submitForm">确 定</el-button>
                  <el-button @click="cancel">取 消</el-button>
               </div>
            </template>
         </el-dialog>
         <DialogQr ref="dialogTinyQr" />
         <DialogCheckwithdrawal ref="dialogCheckwithdrawal" />
      </div>
   </div>
</template>

<script setup name="subject">
import { listSubject, subjectInfo, getSubject, delSubject, addSubject, updateSubject, listSubjectExcludeChild, createRegCode } from "@/api/subject/subject";
import DialogQr from "@/dialog/subject/DialogQr";
import DialogCheckwithdrawal from "@/dialog/subject/DialogCheckwithdrawal"
import { getToken } from '@/utils/auth'
import { ElMessageBox } from 'element-plus'

const route = useRoute();
const router = useRouter();
const { proxy } = getCurrentInstance();
const { sys_normal_disable, sign_type } = proxy.useDict("sys_normal_disable", "sign_type");

const subjectData = ref([]);
const subjectList = ref([]);
const open = ref(false);
const openMine = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const titleMine = ref("");
const subjectOptions = ref([]);
const isExpandAll = ref(true);
const refreshTable = ref(true);
const subject_type = ref(null);
const subject_info = ref({});

const data = reactive({
   user_info: {},
   form: {},
   queryParams: {
      subjectName: undefined,
      delFlag: undefined
   },
   rules: {
      parentId: [{ required: true, message: "上级主体不能为空", trigger: "blur" }],
      subjectName: [{ required: true, message: "主体名称不能为空", trigger: "blur" }],
      orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
      contact: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
   },
   formMine: {},
   rulesMine: {
      parentId: [{ required: true, message: "上级主体不能为空", trigger: "blur" }],
      subjectName: [{ required: true, message: "主体名称不能为空", trigger: "blur" }],
      orderNum: [{ required: true, message: "显示排序不能为空", trigger: "blur" }],
      contact: [{ pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/, message: "请输入正确的手机号码", trigger: "blur" }]
   },
});

const { queryParams, form, rules, user_info, formMine, rulesMine } = toRefs(data);

/** 查询主体列表 */
function getList() {
   loading.value = true;
   listSubject(queryParams.value).then(response => {
      subjectData.value = response.data;
      subjectList.value = proxy.handleTree(response.data, "subjectId");
      loading.value = false;
   });
}
function getSubjectInfo() {
   subjectInfo().then(response => {
      subject_info.value = response.data
      getList();
   })
}
/** 取消按钮 */
function cancel() {
   open.value = false;
   reset();
}
/** 表单重置 */
function reset() {
   form.value = {
      subjectId: undefined,
      parentId: undefined,
      subjectName: undefined,
      orderNum: 0,
      contact: undefined,
      delFlag: "0"
   };
   proxy.resetForm("subjectRef");
}
/** 搜索按钮操作 */
function handleQuery() {
   getList();
}
/** 重置按钮操作 */
function resetQuery() {
   proxy.resetForm("queryRef");
   handleQuery();
}
/** 新增按钮操作 */
function handleAdd(row) {
   reset();
   listSubject().then(response => {
      subjectOptions.value = proxy.handleTree(response.data, "subjectId");
   });
   if (row != undefined) {
      form.value.parentId = row.subjectId;
   }
   open.value = true;
   title.value = "添加主体";
}
/** 展开/折叠操作 */
function toggleExpandAll() {
   refreshTable.value = false;
   isExpandAll.value = !isExpandAll.value;
   nextTick(() => {
      refreshTable.value = true;
   });
}
/** 修改按钮操作 */
function handleUpdate(row) {
   reset();
   listSubjectExcludeChild(row.subjectId).then(response => {
      subjectOptions.value = proxy.handleTree(response.data, "subjectId");
   });
   getSubject(row.subjectId).then(response => {
      form.value = response.data;
      open.value = true;
      title.value = "修改主体";
   });
}
/** 修改按钮操作 */
function handleUpdateMine(row) {
   reset();
   listSubjectExcludeChild(row.subjectId).then(response => {
      subjectOptions.value = proxy.handleTree(response.data, "subjectId");
   });
   getSubject(row.subjectId).then(response => {
      formMine.value = response.data;
      openMine.value = true;
      titleMine.value = "修改主体";
   });
}
/** 提交按钮 */
function submitForm() {
   proxy.$refs["subjectRef"].validate(valid => {
      if (valid) {
         if (form.value.subjectId != undefined) {
            updateSubject(form.value).then(response => {
               proxy.$modal.msgSuccess("修改成功");
               open.value = false;
               getList();
            });
         } else {
            addSubject(form.value).then(response => {
               proxy.$modal.msgSuccess("新增成功");
               open.value = false;
               getList();
            });
         }
      }
   });
}
/** 取消按钮 */
function cancelMine() {
   openMine.value = false;
   resetMine();
}
/** 表单重置 */
function resetMine() {
   formMine.value = {
      subjectId: undefined,
      subjectName: undefined,
      contact: undefined,
   };
   proxy.resetForm("subjectMineRef");
}
/** 提交按钮 */
function submitFormMine() {
   proxy.$refs["subjectMineRef"].validate(valid => {
      if (valid) {
         formMine.value.parentId = null
         updateSubject(formMine.value).then(response => {
            proxy.$modal.msgSuccess("修改成功");
            openMine.value = false;
            getSubjectInfo();
         });
      }
   });
}
function handleCreate() {
   createRegCode().then((response) => {
      proxy.$refs["dialogTinyQr"].open(response.data);
   })
}
function gotoWalletLog() {
   router.push({
      path: "/system/wallet",
   });
}
function gotoSeparate() {
   router.push({
      path: "/system/separate",
   });
}
function gotoWithdrawalLog(){
   router.push({
      path: "/system/withdrawal",
   });
}
function handleWithdrawal() {
   ElMessageBox.prompt('', '请输入提现金额(元)', {
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      closeOnClickModal: false,
      inputValidator: function (value) {
         if (!/^((0{1}.\d{1,2})|([1-9]\d.{1}\d{1,2})|([1-9]+\d)|0)$/.test(value)) {
            return false
         } else {
            return true
         }
      },
      inputErrorMessage: "提现金额只能为正数",
   })
      .then(({ value }) => {
         if (value < 1) {
            proxy.$modal.msgError("提现金额不能低于1元");
            return
         }
         proxy.$refs["dialogCheckwithdrawal"].open((value * 100).toString());
      })
      .catch(() => { });
}
/** 删除按钮操作 */
function handleDelete(row) {
   proxy.$modal.confirm('是否确认删除名称为"' + row.subjectName + '"的数据项?').then(function () {
      return delSubject(row.subjectId);
   }).then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
   }).catch(() => { });
}

user_info.value = JSON.parse(window.localStorage.getItem("user_info"))
subject_type.value = user_info.value.subjectType
getList();
getSubjectInfo();
</script>

<style lang="scss" scoped>
.subject_label {
   margin-right: 10px;
}
</style>
